import os
from .common_func.print_logger import PrintLogger as Logger
import_error_warned = False
try:
    from ruamel import yaml as yaml2
except ModuleNotFoundError:
    if not import_error_warned:
        Logger.warning("UYaml is not valid, because require module:[ruamel-yaml] is not installed. "
                       "If you want use UYaml, please install [ruamel-yaml] first")
        import_error_warned = True

class UYaml:
    @staticmethod
    def load(yaml_file: str):
        res = None
        if not os.path.exists(yaml_file):
            raise FileNotFoundError(f"yaml file: {yaml_file} is not found!")
        with open(yaml_file, "r") as f:
            try:
                _data = f.read()
                # 最新版本的yaml库中去掉了round_trip_dump方法，为了兼容，做一个try-except兼容处理
                try:
                    res = yaml2.round_trip_load(_data)
                except AttributeError:
                    _yaml = yaml2.YAML()
                    res = _yaml.load(_data)
            except Exception as e:
                Logger.error(f"parse yaml file failed, error: {e}, error line:{e.__traceback__.tb_lineno}")
        return res

    @staticmethod
    def dump(obj, yaml_file: str):
        with open(yaml_file, "w") as f:
            # 最新版本的yaml库中去掉了round_trip_dump方法，为了兼容，做一个try-except兼容处理
            try:
                yaml2.round_trip_dump(obj, f)
            except AttributeError:
                _yaml = yaml2.YAML()
                _yaml.dump(obj, f)


if __name__ == "__main__":
    _body = {"title": "test", "ver": 1}
    UYaml.dump(_body, "/tmp/result.yaml")
    _body = UYaml.load("/tmp/result.yaml")
    Logger.system(_body)